//
//  LocalEventsListViewController.m
//  StanfordEvents
//
//  Created by Gongmyung on 7/14/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "LocalEventsListViewController.h"
#import "StanfordEventsAppDelegate.h"


@implementation LocalEventsListViewController

@synthesize eventsArray;
@synthesize managedObjectContext;
@synthesize locationManager;
@synthesize needsUpdate;


#pragma mark -
#pragma mark View lifecycle

- (id)initWithStyle:(UITableViewStyle)style withEvents:(NSMutableArray *)events {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if (self = [super initWithStyle:style]) {
		//set the emoticon database
		eventsArray = events;
        [eventsArray retain];
        needsRefresh = YES;
        needsUpdate = NO;
	}
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    needsRefresh = YES;
    
    // Set the title.
    self.title = @"Nearby Events";
    
    refreshButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refresh)];
    refreshButton.enabled = NO;
    self.navigationItem.rightBarButtonItem = refreshButton;
    
    // Start the location manager.
    [[self locationManager] startUpdatingLocation];
    
    //set the events array
    //  [self setEventsArray:mutableFetchResults];
}


- (void)viewWillAppear:(BOOL)animated {
    if (needsUpdate == YES) {
        
    }
    
    [super viewWillAppear:animated];
}

- (void)addEvent:(Event *)toAdd {
    //insert the event into the table data source array
    [eventsArray insertObject:toAdd atIndex:0];
    [self.tableView reloadData];
    //NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    //[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    //[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

- (void)updateFilters {
    NSLog(@"Filters updated");
}

- (void)refresh {
    refreshButton.enabled = NO;
    NSMutableArray *stuff = [[NSMutableDictionary alloc] init];
    
    //NSLog(@"%d", abs( locationManager.location.coordinate.latitude));
    //NSLog([NSString stringWithFormat:@"Latitude: %@, longitude: %@", [[NSNumber numberWithFloat:locationManager.location.coordinate.latitude] stringValue], [NSNumber numberWithFloat:locationManager.location.coordinate.longitude]]);
    
    [stuff setValue:[NSNumber numberWithFloat:locationManager.location.coordinate.latitude] forKey:@"latitude"];
    [stuff setValue:[NSNumber numberWithFloat:locationManager.location.coordinate.longitude] forKey:@"longitude"];
    [stuff setValue:[NSNumber numberWithDouble:.8] forKey:@"radius"];
    
    //before we fire the thread, get the last entry in our principal list stream and send the id
    /*
    NSString *username, *password;
    NSUserDefaults *defaultSettings = [NSUserDefaults standardUserDefaults];
    username = [defaultSettings stringForKey:@"username"];
    password = [defaultSettings stringForKey:@"password"];
    
    NSURL *url = [NSURL URLWithString:@"http://colby.stanford.edu/community_vibe/concierge/rpc.php"];
    ASIFormDataRequest *principalRequest = [ASIFormDataRequest requestWithURL:url];
    [principalRequest setPostValue:username forKey:@"name"];
    [principalRequest setPostValue:password forKey:@"key"];
    [principalRequest setPostValue:@"getPrincipalInterestStream" forKey:@"do"];
    [principalRequest setPostValue:@"" forKey:@"since"];    
    [principalRequest setPostValue:@"1" forKey:@"limit"];
    [principalRequest startSynchronous];
    NSString *response;
    NSError *error = [principalRequest error];
    if (!error) {
        response = [principalRequest responseString];
        //NSLog(response);
    }
    SBJSON *parser = [[SBJSON alloc] init];
    NSArray *jsonResponse = [parser objectWithString:response];
    if (jsonResponse.count != 0) {
        NSDictionary *mid = [jsonResponse objectAtIndex:0];
        [stuff setValue:[mid objectForKey:@"mid"] forKey:@"lastmid"];
    }
    else {
        [stuff setValue:@"1" forKey:@"mid"];
    }
     */
    [NSThread detachNewThreadSelector:@selector(startDownload:) toTarget:self withObject:stuff];
}

/*
 * Method for downloading in background thread
 */
- (void)startDownload:(NSMutableDictionary*)stuff {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSString *username, *password;
    NSUserDefaults *defaultSettings = [NSUserDefaults standardUserDefaults];
    username = [defaultSettings stringForKey:@"username"];
    password = [defaultSettings stringForKey:@"password"];
    
    NSMutableDictionary *requestDict = [[NSMutableDictionary alloc] init];
    [requestDict setObject:[[stuff objectForKey:@"latitude"] stringValue] forKey:@"latitude"];
    [requestDict setObject:[[stuff objectForKey:@"longitude"] stringValue] forKey:@"longitude"];
    //one degree of latitude = 69 miles, do a simple conversion here (divide by 2 for radius):
    [requestDict setObject:[stuff objectForKey:@"radius"] forKey:@"radius"];
    [requestDict setObject:[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]] forKey:@"starttime"];
    [requestDict setObject:[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]] forKey:@"endtime"];
    
    //parse object into json
    SBJSON *sparser = [[SBJSON alloc] init];
    NSString *jsonEvent = [sparser stringWithObject:requestDict];
    
    //create a post request
    NSURL *url = [NSURL URLWithString:@"http://colby.stanford.edu/community_vibe/concierge/rpc.php"];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    
    [request setPostValue:username forKey:@"name"];
    [request setPostValue:password forKey:@"key"];
    [request setPostValue:@"postMessage" forKey:@"do"];
    [request setPostValue:jsonEvent forKey:@"content"];    
    [request setPostValue:@"stanford_events,find" forKey:@"tags"];
    NSLog(@"Sending local events list update request to concierge");
    [request startSynchronous];
    
    NSString *response;
    NSError *error = [request error];
    if (!error) {
        response = [request responseString];
        //NSLog(response);
    }
    
    //set state to 2 so that we know how to respond when we get a push
    StanfordEventsAppDelegate *appDelegate = (StanfordEventsAppDelegate*)[[UIApplication sharedApplication] delegate];
    appDelegate.state = 2;
    
    /*
    //check our concierge principle until we get a response, if nothing after 10 seconds quit
    int count = 0;
    ASIFormDataRequest *principalRequest = [ASIFormDataRequest requestWithURL:url];
    NSString *lastEvent = [stuff objectForKey:@"lastmid"];
    while ( count < 5 ) {
        [NSThread sleepForTimeInterval:1];
        
        [principalRequest setPostValue:username forKey:@"name"];
        [principalRequest setPostValue:password forKey:@"key"];
        [principalRequest setPostValue:@"getPrincipalInterestStream" forKey:@"do"];
        [principalRequest setPostValue:lastEvent forKey:@"since"];    
        [principalRequest setPostValue:@"10" forKey:@"limit"];
        [principalRequest startSynchronous];
        
        error = [principalRequest error];
        if (!error) {
            response = [principalRequest responseString];
            //NSLog(response);
        }
        //if we have a response, parse it and add events
        if( response.length != 0 ) {
            NSArray *jsonResponse = [sparser objectWithString:response];
            
            if( jsonResponse.count != 0 ) {
                NSDictionary *jsonResponseDict = [jsonResponse objectAtIndex:0];
                NSString *taglist = [jsonResponseDict objectForKey:@"taglist"];
                if( [taglist hasPrefix:@"response, stanford_events"] ) {
                    NSString *eventDataString = [jsonResponseDict objectForKey:@"content"];
                    NSArray *eventData = [sparser objectWithString:eventDataString];
                    [self performSelectorOnMainThread:@selector(downloadFinished:) withObject:eventData waitUntilDone:NO];
                    break;
                }
            }
        }
        else {
            refreshButton.enabled = YES;
        }
        
        count += 1;
    }
     */
    
    [sparser release];
    [stuff release];
    [requestDict release];
    [pool release]; 
}

/*
 * Method that's called when the download is finished
 */
- (void)downloadFinished:(NSString*)eventsToParse {
    NSError *error;
    SBJSON *parser = [[SBJSON alloc] init];
    NSLog(@"About to add downloaded events to nearby events view");
    [eventsToParse retain];
    
    NSArray *messages = [parser objectWithString:eventsToParse];
    for (NSString *message in messages) {
        NSArray *jsonResponseArray = [parser objectWithString:eventsToParse];
        NSDictionary *jsonResponseDict = [jsonResponseArray objectAtIndex:0];
        //NSString *taglist = [jsonResponseDict objectForKey:@"taglist"];
        NSString *eventDataString = [jsonResponseDict objectForKey:@"content"];
        ////fix later[taglist     [taglist hasPrefix:@"response, stanford_events"]
        if( eventDataString.length > 0 ) {
            NSString *eventDataString = [jsonResponseDict objectForKey:@"content"];
            NSDictionary *eventData = [parser objectWithString:eventDataString];
            
            bool isInArray = NO;
            for( Event *e in eventsArray ) {
                if ([e.eid intValue] == [[eventData objectForKey:@"eid"] intValue]) {
                    isInArray = YES;
                }
            }
                
            if( !isInArray ) {
                NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
                [request setEntity:[NSEntityDescription entityForName:@"Event" inManagedObjectContext:managedObjectContext]];
                [request setPredicate:[NSPredicate predicateWithFormat:@"eid==%@", [eventData objectForKey:@"eid"]]];
                NSArray *results = [managedObjectContext executeFetchRequest:request error:&error];
                if( results.count == 0 ) {
                    Event *event = (Event *)[NSEntityDescription insertNewObjectForEntityForName:@"Event" inManagedObjectContext:managedObjectContext];
                    
                    [event setTitle:[eventData objectForKey:@"title"]];
                    [event setEid:[NSNumber numberWithDouble:[[eventData objectForKey:@"eid"] doubleValue]]];
                    [event setEventdescription:[eventData objectForKey:@"description"]];
                    [event setEventtype:[NSNumber numberWithDouble:[[eventData objectForKey:@"eventtype"] doubleValue]]];
                    [event setHost:[eventData objectForKey:@"host"]];
                    [event setStarttime:[NSDate dateWithTimeIntervalSince1970:[[eventData objectForKey:@"starttime"] doubleValue]]];
                    [event setEndtime:[NSDate dateWithTimeIntervalSince1970:[[eventData objectForKey:@"endtime"] doubleValue]]];
                    [event setLocation:[eventData objectForKey:@"location"]];
                    [event setLatitude:[NSNumber numberWithDouble:[[eventData objectForKey:@"latitude"] doubleValue]]];
                    [event setLongitude:[NSNumber numberWithDouble:[[eventData objectForKey:@"longitude"] doubleValue]]];
                    [event setCreated:[NSDate dateWithTimeIntervalSince1970:[[eventData objectForKey:@"created"] doubleValue]]];
                    
                    [eventsArray insertObject:event atIndex:0];
                    //NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
                    //[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
                    //[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
                }
                else {
                    Event *event = [results objectAtIndex:0];
                    [eventsArray insertObject:event atIndex:0];
                    //NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
                    //[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
                    //[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
                }
            }
        }
    }

    if (![managedObjectContext save:&error]) {
        NSLog(@"failed to save created event");
    }
    
    [eventsToParse release];
    [parser release];
    [self.tableView reloadData];
    refreshButton.enabled = YES;
}

/*
 - (void)viewDidAppear:(BOOL)animated {
 [super viewDidAppear:animated];
 }
 */
/*
 - (void)viewWillDisappear:(BOOL)animated {
 [super viewWillDisappear:animated];
 }
 */
/*
 - (void)viewDidDisappear:(BOOL)animated {
 [super viewDidDisappear:animated];
 }
 */
/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [eventsArray count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // A date formatter for the time stamp
    static NSDateFormatter *dateFormatter = nil;
    if (dateFormatter == nil) {
        dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
        [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    }
    
    static NSString *CellIdentifier = @"Cell";
    
    // Dequeue or create a new cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
    
    Event *event = (Event *)[eventsArray objectAtIndex:indexPath.row];
    
    cell.textLabel.text = [event title];
    cell.detailTextLabel.text = [dateFormatter stringFromDate:[event starttime]];
    if( [event.attended intValue] == 1 ) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    
    return cell;
}


/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */


/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }   
 }
 */


/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */


/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	
    EventDetailTableViewController *detailViewController = [[EventDetailTableViewController alloc] initWithStyle:UITableViewStyleGrouped withEvent:[eventsArray objectAtIndex:indexPath.row] ];
    // ...
    // Pass the selected object to the new view controller.
    detailViewController.delegate = self;
    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];
}

//delegate methods
- (void) didCheckIn {
    [self.tableView reloadData];
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}


/*
 * Accessor method that dynamically creates a core location manager
 */
- (CLLocationManager *)locationManager {
    if (locationManager != nil) {
        return locationManager;
    }
    
    locationManager = [[CLLocationManager alloc] init];
    locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
    locationManager.delegate = self;
    
    return locationManager;
}

/*
 * Core Location Manager Delegate Methods
 */
- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation {
    
    if( needsRefresh == YES ) {
        [self refresh];
        needsRefresh = NO;
    }
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    //addButton.enabled = NO;
}


//publish event view controller delegate methods
- (UINavigationController *)navController {
    return self.navigationController;
}

- (void)viewDidUnload {
    self.eventsArray = nil;
    self.locationManager = nil;
}

- (void)dealloc {
    [managedObjectContext release];
    [eventsArray release];
    [locationManager release];
    [super dealloc];
}


@end

